﻿using System.Linq.Expressions;
using AutoMapper;
using DevProtocolApi.Dtos.system;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.EntityModel.Auth;
using Model.EntityModel.SysModel;
using Model.QueryModel.system;
using Service.IService.ISysService;
using Service.Service.SysService;
using SqlSugar;

namespace DevProtocolApi.Controllers.sysControllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserMasterController : BaseController
    {
        private readonly IUserService _userService;
        private readonly ILogger<UserMasterController> _logger;
        private readonly IMapper _mapper;

        public UserMasterController(
            IUserService userService,
            ILogger<UserMasterController> logger,
            IMapper mapper)
        {
            _userService = userService;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户信息</returns>
        [HttpGet("{userId}")]
        public IActionResult GetUser(string userId)
        {
            try
            {
                var user = _userService.GetUserById(userId);
                return user != null
                    ? Success(user)
                    : Failed("用户不存在");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户信息失败，用户ID: {userId}");
                return Failed($"获取失败: {ex.Message}");
            }
        }
        

        [HttpPost]
        public IActionResult GetUserPage(int pageNum, int pageSize, QueryUser search)
        {
            try
            {
                var user = _userService.GetUserPage(pageNum, pageSize, search);
                return user != null
                    ? Success(user)
                    : Failed("用户不存在");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户信息失败!");
                return Failed($"获取失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 创建新用户
        /// </summary>
        /// <param name="dto">用户信息DTO</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public IActionResult Create([FromBody] UserMasterDto dto)
        {
            try
            {
                var user = _mapper.Map<User>(dto);
                bool success = _userService.CreateUser(user);
                return success
                    ? Success("用户创建成功")
                    : Failed("用户创建失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建用户失败: {dto.UserName}");
                return Failed($"创建失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="dto">用户信息DTO</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public IActionResult Update([FromBody] UserMasterDto dto)
        {
            try
            {
                var user = _mapper.Map<User>(dto);
                bool success = _userService.UpdateUser(user);
                return success
                    ? Success("用户更新成功")
                    : Failed("用户更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户失败: {dto.UserId}");
                return Failed($"更新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="status">新状态(A:激活/I:失效)</param>
        /// <returns>操作结果</returns>
        [HttpPost("status/{userId}")]
        public IActionResult UpdateStatus(string userId, [FromBody] string status)
        {
            try
            {
                bool success = _userService.UpdateUserStatus(userId, status);
                return success
                    ? Success("用户状态更新成功")
                    : Failed("用户状态更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户状态失败: {userId}");
                return Failed($"更新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加组别到用户
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="groupIds">组别ID列表</param>
        /// <returns>操作结果</returns>
        [HttpPost("groups/{userId}")]
        public IActionResult AddGroups(string userId, [FromBody] List<string> groupIds)
        {
            try
            {
                bool success = _userService.AddGroupsToUser(userId, groupIds);
                return success
                    ? Success("添加组别成功")
                    : Failed("添加组别失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加组别到用户失败: {userId}");
                return Failed($"添加失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从用户移除组别
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="groupIds">组别ID列表</param>
        /// <returns>操作结果</returns>
        [HttpDelete("groups/{userId}")]
        public IActionResult RemoveGroups(string userId, [FromBody] List<string> groupIds)
        {
            try
            {
                bool success = _userService.RemoveGroupsFromUser(userId, groupIds);
                return success
                    ? Success("移除组别成功")
                    : Failed("移除组别失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从用户移除组别失败: {userId}");
                return Failed($"移除失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户关联的组别
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>组别列表</returns>
        [HttpGet("groups/{userId}")]
        public IActionResult GetUserGroups(string userId)
        {
            try
            {
                var groups = _userService.GetUserGroups(userId);
                return Success(groups);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户组别失败: {userId}");
                return Failed($"获取失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户可用的组别
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>可用组别列表</returns>
        [HttpGet("available-groups/{userId}")]
        public IActionResult GetAvailableGroups(string userId)
        {
            try
            {
                var groups = _userService.GetAvailableGroupsForUser(userId);
                return Success(groups);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取可用组别失败: {userId}");
                return Failed($"获取失败: {ex.Message}");
            }
        }
    }
}